<?php
require_once 'database/MySQL.php';

class User {
	
	private $grocerylist;
	
	public function __construct(){
		$this->grocerylist = new GrosseryList();
	}
	
	/**
	 * Creates a user in the database and creates an grocerylist for the user
	 * Returns true if the inserts succeeded
	 * @param string $name		- name of the user
	 * @param string $password	- password of the user
	 */
	public function createUser($name, $password){
		$query = sprintf("	INSERT INTO `user`(name, password, tag)
							VALUES('%s', '%s', CURRENT_TIMESTAMP)", 
							mysql_escape_string($name),
							mysql_escape_string($password));
		if(!MySQL::execute($query)){
			return false;
		}
		$id = $this->getUserId($name, $password);
		$name = "Boodschappenlijst van " . $name;
		if(!$this->grocerylist->createGrosseryList($id, $name)){
			return false;
		}
		return true;
	}
	
	/**
	 * Reads a user from the database by its name an password
	 * Returns an ArrayObject containing the user
	 * @param String $name		-	name of the user
	 * @param String $password	-	password of the user
	 */
	public function readUser($name, $password){
		$query = sprintf("SELECT user.id AS 'id',
						user.name AS 'name', 
						user.password AS 'password', 
						grossery_list.id AS 'listid'
						FROM `user` INNER JOIN `grossery_list`
						ON user.id = grossery_list.user
						WHERE user.name = '%s'
						AND user.password = '%s'",
						mysql_real_escape_string($name),
						mysql_real_escape_string($password));
		return MySQL::getArrayObject($query);
	}
	
	/**
	* Reads a user from the database by tag id
	* Returns an ArrayObject containing the user
	* @param String $name		-	name of the user
	* @param String $password	-	password of the user
	*/
	public function readUserByTag($tag){
		$query = sprintf("SELECT user.id AS 'id',
							user.name AS 'name', 
							user.password AS 'password', 
							grossery_list.id AS 'listid'
							FROM `user` INNER JOIN (`grossery_list`, `tag`)
							ON (user.id = grossery_list.user AND user.tag = tag.id)
							WHERE tag.name = '%s'",
							mysql_real_escape_string($tag));
		return MySQL::getArrayObject($query);
	}

	/**
	 * Returns the id of the user based on its name and password
	 * 
	 * @param string $name
	 * @param string $password
	 */
	public function getUserId($name, $password){
		$query = sprintf("SELECT id
						FROM `user`
						WHERE name = '%s'
						AND password = '%s'",
						mysql_real_escape_string($name),
						mysql_real_escape_string($password));
		return MySQL::getFirstResult($query);
	}
}